/**
 * iOS权限管理工具类
 * 提供统一的权限检查、请求和错误处理
 */

import permision from '@/utils/permission.js'

class PermissionManager {
  constructor() {
    this.isIOS = uni.getSystemInfoSync().platform === 'ios'
  }

  /**
   * 检查并请求所有必要的权限
   * @param {Array} permissions 权限列表 ['camera', 'photoLibrary', 'record']
   * @returns {Promise<boolean>} 是否所有权限都已获取
   */
  async checkAndRequestAllPermissions(permissions = ['camera', 'photoLibrary', 'record']) {
    if (!this.isIOS) {
      return true // Android权限处理逻辑
    }

    const permissionMessages = {
      camera: '相机权限',
      photoLibrary: '相册权限', 
      record: '麦克风权限'
    }

    const permissionDescriptions = {
      camera: '需要相机权限来录制视频',
      photoLibrary: '需要相册权限来保存视频',
      record: '需要麦克风权限来录制音频'
    }

    for (const permission of permissions) {
      const hasPermission = await permision.checkAndRequestPermission(permission)
      if (!hasPermission) {
        const result = await this.showPermissionDialog(
          permissionMessages[permission],
          permissionDescriptions[permission]
        )
        if (!result) {
          return false
        }
      }
    }
    return true
  }

  /**
   * 显示权限对话框
   * @param {string} permissionName 权限名称
   * @param {string} description 权限描述
   * @returns {Promise<boolean>} 用户是否选择去设置
   */
  showPermissionDialog(permissionName, description) {
    return new Promise((resolve) => {
      uni.showModal({
        title: '权限提示',
        content: `${description}，请在设置中开启${permissionName}`,
        showCancel: true,
        cancelText: '取消',
        confirmText: '去设置',
        success: (res) => {
          if (res.confirm) {
            permision.gotoAppPermissionSetting()
            resolve(true)
          } else {
            resolve(false)
          }
        },
        fail: () => {
          resolve(false)
        }
      })
    })
  }

  /**
   * 检查单个权限状态
   * @param {string} permission 权限类型
   * @returns {boolean} 是否有权限
   */
  checkPermission(permission) {
    if (!this.isIOS) {
      return true
    }
    return permision.judgeIosPermission(permission)
  }

  /**
   * 请求单个权限
   * @param {string} permission 权限类型
   * @returns {Promise<boolean>} 是否获取权限
   */
  async requestPermission(permission) {
    if (!this.isIOS) {
      return true
    }
    return await permision.checkAndRequestPermission(permission)
  }

  /**
   * 获取权限状态描述
   * @param {string} permission 权限类型
   * @returns {string} 权限状态描述
   */
  getPermissionStatusDescription(permission) {
    const status = this.checkPermission(permission)
    const permissionNames = {
      camera: '相机',
      photoLibrary: '相册',
      record: '麦克风'
    }
    return status ? `${permissionNames[permission]}权限已开启` : `${permissionNames[permission]}权限未开启`
  }
}

// 创建单例实例
const permissionManager = new PermissionManager()

export default permissionManager
